<template>
	<view id="app" class="container">
		       <!-- <div class="header">
		            <h1><i class="fas fa-eye"></i> 电脑验光仪筛查系统</h1>
		            <p>扫描设备码和学生档案编码获取验光数据</p>
		        </div> -->
		        
		        <!-- 扫码区域 -->
		       <!-- <div class="scan-section">
		            <button class="scan-btn" @click="scanDeviceCode">
		                <i class="fas fa-camera"></i> 扫描设备码
		            </button>
		        </div> -->
		        
		        <!-- 设备区域显示 -->
		       <div class="device-info" :class="{ disconnected: !device.isConnected }">
		           <div class="device-label">
		               {{ device.isConnected ? '已连接' : '未连接' }}
		           </div>
		           <div class="device-value">
		               {{ device.isConnected ? device.deviceCode : '暂无设备' }}{{ device.isConnected ? device.deviceName : '' }}
		           </div>
		       </div>
		        
		        <!-- 筛查信息卡片 -->
		        <div class="card">
		            <div class="card-title">
		                <i class="fas fa-clipboard-list"></i>
		                <h2>筛查信息</h2>
		            </div>
		            
		            <div class="screening-info">
		                <!-- 学生基本信息 -->
		                <div>
<!-- 		                    <h3 class="section-title">学生基本信息</h3> -->
		                    <div class="info-grid">
		                        <div class="info-item">
<!-- 		                            <div class="info-label">学生信息</div> -->
		                            <div class="info-value">{{ studentInfo.studentId || '暂无信息' }} {{ studentInfo.studentName || '' }}   {{ studentInfo.className || '' }}</div>
		                        </div>
		                        <!-- <div class="info-item">
		                            <div class="info-label">学生姓名</div>
		                            <div class="info-value">{{ studentInfo.studentName }}</div>
		                        </div>
		                        <div class="info-item">
		                            <div class="info-label">学校名称</div>
		                            <div class="info-value">{{ studentInfo.schoolName }}</div>
		                        </div>
		                        <div class="info-item">
		                            <div class="info-label">年级</div>
		                            <div class="info-value">{{ studentInfo.gradeName }}</div>
		                        </div>
		                        <div class="info-item">
		                            <div class="info-label">班级</div>
		                            <div class="info-value">{{ studentInfo.className }}</div>
		                        </div>
		                        <div class="info-item">
		                            <div class="info-label">筛查日期</div>
		                            <div class="info-value">{{ screeningDate }}</div>
		                        </div>
		                        <div class="info-item">
		                            <div class="info-label">筛查人员</div>
		                            <div class="info-value">{{ screeningPerson }}</div>
		                        </div> -->
		                    </div>
		                </div>
		                
		                <!-- 验光数据表格 -->
		                <div>
<!-- 		                    <h3 class="section-title">验光数据</h3> -->
		                    <div class="vision-table-container">
		                        <table class="vision-table">
		                            <thead>
		                                <tr>
		                                    <th>项目</th>
											<th>右眼</th>
		                                    <th>左眼</th>
		                                </tr>
		                            </thead>
		                            <tbody>
		                               <!-- <tr>
		                                    <td>眼别</td>
		                                    <td class="eye-left"><span class="eye-label">{{ visionData.left.eyeType }}</span></td>
		                                    <td class="eye-right"><span class="eye-label">{{ visionData.right.eyeType }}</span></td>
		                                </tr> -->
		                                <tr>
		                                    <td>S (球镜)</td>
											<td><span class="data-value">{{ visionData.right.sphere }} D</span></td>
		                                    <td><span class="data-value">{{ visionData.left.sphere }} D</span></td>
		                                </tr>
		                                <tr>
		                                    <td>C (柱镜)</td>
											<td><span class="data-value">{{ visionData.right.cylinder }} D</span></td>
		                                    <td><span class="data-value">{{ visionData.left.cylinder }} D</span></td>
		                                </tr>
		                                <tr>
		                                    <td>A (轴向)</td>
											<td><span class="data-value">{{ visionData.right.axis }} °</span></td>
		                                    <td><span class="data-value">{{ visionData.left.axis }} °</span></td>
		                                </tr>
										<tr>
										    <td>散光符号</td>
											<td><span class="data-value">{{ visionData.right.astigmatismSign }}</span></td>
										    <td><span class="data-value">{{ visionData.left.astigmatismSign }}</span></td>
										</tr>
										<tr>
										    <td>SE (等效球镜)</td>
											<td><span class="data-value">{{ visionData.right.se }} D</span></td>
										    <td><span class="data-value">{{ visionData.left.se }} D</span></td>
										</tr>
										<tr>
										    <td>PD (瞳距)</td>
											<td><span class="data-value">{{ visionData.right.pd }} mm</span></td>
										    <td><span class="data-value">{{ visionData.left.pd }} mm</span></td>
										</tr>
										<tr>
										    <td>VD (镜眼距)</td>
											<td><span class="data-value">{{ visionData.right.vd }} mm</span></td>
										    <td><span class="data-value">{{ visionData.left.vd }} mm</span></td>
										</tr>
										
		                               <!-- <tr>
		                                    <td>矫正视力</td>
		                                    <td><span class="data-value">{{ visionData.left.correctedVision }}</span></td>
		                                    <td><span class="data-value">{{ visionData.right.correctedVision }}</span></td>
		                                </tr>
		                                <tr>
		                                    <td>裸眼视力</td>
		                                    <td><span class="data-value">{{ visionData.left.uncorrectedVision }}</span></td>
		                                    <td><span class="data-value">{{ visionData.right.uncorrectedVision }}</span></td>
		                                </tr>
		                                <tr>
		                                    <td>瞳孔直径</td>
		                                    <td><span class="data-value">{{ visionData.left.pupilDiameter }} mm</span></td>
		                                    <td><span class="data-value">{{ visionData.right.pupilDiameter }} mm</span></td>
		                                </tr>
		                                <tr>
		                                    <td>角膜曲率</td>
		                                    <td><span class="data-value">{{ visionData.left.cornealCurvature }}</span></td>
		                                    <td><span class="data-value">{{ visionData.right.cornealCurvature }}</span></td>
		                                </tr> -->
		                            </tbody>
		                        </table>
		                    </div>
		                </div>
		            </div>
		        </div>
		        
		        <!-- 操作按钮区域 -->
		        <div class="action-section">
		          <button class="action-btn" @click="scanDevice"><i class="fas fa-camera"></i><span>连设备</span></button>
		          <button class="action-btn" @click="scanStudentCode"><i class="fas fa-id-card"></i><span>扫学生</span></button>
		          <button class="action-btn" @click="getVisionData"><i class="fas fa-search"></i><span>读数据</span></button>
		          <button class="action-btn" @click="saveData"><i class="fas fa-save"></i><span>保存</span></button>
		          <button class="action-btn" @click="resetData"><i class="fas fa-redo"></i><span>重置</span></button>
		          <button class="action-btn" @click="showToast('更多')"><i class="fas fa-ellipsis-h"></i><span>更多</span></button>
		        </div>
	</view>
</template>

<script>
	import {getDnygScData,dnygScAdd } from "@/api/files/screenPlanInfo";
	export default {
		data() {
			return {
				device:{
					deviceCode: '',
					deviceName: '',
					isConnected: false,
				},
				studentInfo: {
					planId: "",
					studentId: "",
					studentName: "",
					schoolName: "",
					gradeName: "",
					className: "",
					screenType: "",
				},
				visionData: {
					left: {
						eyeType: "",
						pd: "",
						vd: "",
						se: "",
						astigmatismSign: "",
						sphere: "",
						cylinder: "",
						axis: "",
						correctedVision: "",
						uncorrectedVision: "",
						pupilDiameter: "",
						cornealCurvature: ""
					},
					right: {
						eyeType: "",
						pd: "",
						vd: "",
						se: "",
						astigmatismSign: "",
						sphere: "",
						cylinder: "",
						axis: "",
						correctedVision: "",
						uncorrectedVision: "",
						pupilDiameter: "",
						cornealCurvature: ""
					}
				},
				screeningDate: new Date().toLocaleDateString(),
				screeningPerson: '李医生'
			}
		},
		 methods: {
				// 扫描连接设备
				scanDevice() {
					// this.device.isConnected = true;
					// this.device.deviceCode = 'DEV2023001-';
					// this.device.deviceName = '验光仪-A';
					uni.scanCode({
						success: (res) => {
							console.log('设备码扫描结果:', res.result);
							const smResult  = res.result.split(',');
							this.device.deviceCode = smResult[1];
							this.device.deviceName = smResult[2];
							this.device.isConnected = true;
							this.resetData();
							uni.showToast({ title: '设备连接成功', icon: 'success' });
						},
						fail: (err) => {
							console.log('扫码失败:', err);
							this.device.isConnected = false;
							this.device.deviceCode = '';
							this.device.deviceName = '';
							uni.showToast({ title: '设备连接失败', icon: 'none' })
						}
					});
				},
				// 扫描学生档案编码
				scanStudentCode() {
					uni.scanCode({
						success: (res) => {
							console.log('学生档案编码扫描结果:', res.result);
							const smResult  = res.result.split(',');
							this.studentInfo.planId =smResult[1]
							this.studentInfo.studentId =smResult[5]
							this.studentInfo.studentName =smResult[2]
							this.studentInfo.className =smResult[6]
							this.studentInfo.screenType=smResult[4]
							uni.showToast({ title: '学生信息获取成功', icon: 'success' });
						},
						fail: (err) => {
							console.log('扫码失败:', err);
							this.resetData();
							uni.showToast({ title: '扫码失败', icon: 'none' })
						}
					});
				},
				
				// 获取视力数据
				getVisionData() {
				  if (this._getting) return          // 1. 防重
				  this._getting = true
				  uni.showToast({ title: '正在获取', icon: 'none' })
				  const deviceCode = this.device.deviceCode
				  if (!deviceCode) {
				    uni.showToast({ title: '设备未连接', icon: 'none' })
				    uni.hideLoading()
				    this._getting = false
				    return
				  }
				
				  getDnygScData(deviceCode)
				    .then(res => {
				      this.visionData = res.data
				      uni.showToast({ title: '获取成功', icon: 'success' })
				    })
				    .catch(err => {
				      console.error('获取失败：', err)
                     let errorMsg = e.message || '获取失败，请重试'
				      uni.showToast({ title: errorMsg, icon: 'none' })
				    })
				    .finally(() => {
				      uni.hideLoading()
				      this._getting = false   // 2. 必解锁
				    })
				},
				
				// 保存数据
				saveData: async function () {
				  if (this._saving) return          // 1. 简单锁
				  this._saving = true
				  uni.showLoading({ title: '正在保存...', mask: true })
				  // 2. 准备数据
				  const record = {
				    deviceNumber: this.device.deviceCode,
				    studentId: this.studentInfo.studentId,
					studentName: this.studentInfo.studentName,
				    dnSlREye: this.visionData.right.se,
				    dnSlLEye: this.visionData.left.se,
				    rightSpherical: this.visionData.right.sphere,
				    rightCylindrical: this.visionData.right.cylinder,
				    rightAxis: this.visionData.right.axis,
				    leftSpherical: this.visionData.left.sphere,
				    leftCylindrical: this.visionData.left.cylinder,
				    leftAxis: this.visionData.left.axis,
				    screenType: this.studentInfo.screenType,
					planId: this.studentInfo.planId,
				  }
				
				  // 3. 校验（显式判 null/undefined）
				  const assert = (val, msg) => {
				    if (val == null || val === '') throw new Error(msg);
				  };
				  try {
				    assert(record.deviceNumber, '设备未连接')
				    assert(record.studentId, '筛查用户信息不能为空')
				    assert(record.dnSlREye, '右眼筛查信息不能为空')
				    assert(record.dnSlLEye, '左眼筛查信息不能为空')
				  } catch (e) {
				    uni.showToast({ title: e.message, icon: 'none' })
				    uni.hideLoading()
				    this._saving = false
				    return
				  }
				  // 4. 真正请求 + 统一异常
				  try {
				    const res = await dnygScAdd(record)        // 返回 Promise
				    if (res.code === 200) {
				      uni.showToast({ title: '保存成功', icon: 'success', duration: 3000 })
				      this.resetData()
				    } else {
				      throw new Error(res.msg || res.message || '保存失败')
				    }
				  } catch (e) {
				    // 网络异常、http 非 200、业务码异常都走到这里
				    uni.showModal({
				      title: '保存失败',
				      content: e.message || '网络异常，是否重试？',
				      showCancel: true,
				      success: (ans) => {
				        if (ans.confirm) this.saveData()   // 用户点重试
				      }
				    })
				  } finally {
				    uni.hideLoading()
				    this._saving = false
				  }
				},

				// 重置数据
				resetData() {
					this.studentInfo = {
						studentId: "",
						studentName: "",
						schoolName: "",
						gradeName: "",
						className: "",
						planId: "",
						screenType: "",
					};
					this.visionData = {
						left: {
							eyeType: "",
							pd: "",
							vd: "",
							se: "",
							astigmatismSign: "",
							sphere: "",
							cylinder: "",
							axis: "",
							correctedVision: "",
							uncorrectedVision: "",
							pupilDiameter: "",
							cornealCurvature: ""
						},
						right: {
							eyeType: "",
							pd: "",
							vd: "",
							se: "",
							astigmatismSign: "",
							sphere: "",
							cylinder: "",
							axis: "",
							correctedVision: "",
							uncorrectedVision: "",
							pupilDiameter: "",
							cornealCurvature: ""
						}
					};
				},
				
				// 工具函数 - 显示提示
				showToast(title, icon) {
					if (typeof uni !== 'undefined') {
						uni.showToast({ title, icon });
					} else {
						alert(title);
					}
				},
				
				// 工具函数 - 显示加载
				showLoading(title) {
					if (typeof uni !== 'undefined') {
						uni.showLoading({ title });
					} else {
						console.log(title);
					}
				},
				
				// 工具函数 - 隐藏加载
				hideLoading() {
					if (typeof uni !== 'undefined') {
						uni.hideLoading();
					}
				}
			}
	}
</script>

<style>
/* 	@import url('https://cdn.staticfile.org/font-awesome/6.4.2/css/all.min.css'); */
	.container {
		background-color: #f2f2f2;
		min-height: 100vh;
		max-width: 1200px;
		margin: 0 auto;
		color: #333;
		padding: 15px;
	}
	
	.header {
		text-align: center;
		margin-bottom: 20px;
		padding: 15px;
		background: white;
		border-radius: 8px;
		box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
	}
	
	.header h1 {
		color: #2c3e50;
		font-size: 20px;
		margin-bottom: 5px;
	}
	
	.header p {
		color: #7f8c8d;
		font-size: 13px;
	}
	
	.card {
		background: white;
		border-radius: 8px;
		padding: 15px;
		margin-bottom: 15px;
		box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
	}
	
	.card-title {
		display: flex;
		align-items: center;
		margin-bottom: 12px;
		padding-bottom: 8px;
		border-bottom: 1px solid #eee;
	}
	
	.card-title i {
		margin-right: 8px;
		color: #3498db;
		font-size: 16px;
	}
	
	.card-title h2 {
		color: #2c3e50;
		font-size: 16px;
	}
	
	.scan-section {
		display: flex;
		justify-content: space-between;
		gap: 12px;
		margin-bottom: 15px;
	}
	
	.scan-btn {
		flex: 1;
		background: #3498db;
		color: white;
		border: none;
		padding: 10px;
		border-radius: 5px;
		font-size: 14px;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.scan-btn i {
		margin-right: 6px;
		font-size: 14px;
	}
	
	.device-info {
		background: #e8f4fd;
		border-radius: 5px;
		padding: 10px;
		margin-bottom: 15px;
		border-left: 3px solid #3498db;
	}
	.device-info.disconnected {
	    background: #fee;
	    border-left-color: #e74c3c;
	}
	.device-info.disconnected .device-label {
	    color: #e74c3c;
	}
	.device-label {
		font-weight: 600;
		color: #2980b9;
		margin-bottom: 3px;
		font-size: 12px;
	}
	
	.device-value {
		font-size: 14px;
		color: #2c3e50;
	}
	
	.screening-info {
		margin-bottom: 15px;
	}
	
	.section-title {
		font-size: 15px;
		color: #2c3e50;
		margin-bottom: 10px;
		padding-bottom: 6px;
		border-bottom: 1px solid #eee;
	}
	
	.info-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
		gap: 10px;
		margin-bottom: 15px;
	}
	
	.info-item {
		display: flex;
		flex-direction: column;
	}
	
	.info-label {
		font-weight: 600;
		color: #7f8c8d;
		margin-bottom: 3px;
		font-size: 12px;
	}
	
	.info-value {
		font-size: 14px;
		color: #2c3e50;
		padding: 5px 8px;
		background: #f8f9fa;
		border-radius: 3px;
		border-left: 2px solid #3498db;
	}
	
	.vision-table-container {
		overflow-x: auto;
		margin-bottom: 15px;
	}
	
	.vision-table {
		width: 100%;
		border-collapse: collapse;
		font-size: 14px;
	}
	
	.vision-table th {
		background: #f8f9fa;
		color: #2c3e50;
		font-weight: 600;
		padding: 8px 10px;
		text-align: left;
		border-bottom: 1px solid #eaeaea;
	}
	
	.vision-table td {
		padding: 8px 10px;
		border-bottom: 1px solid #f0f0f0;
	}
	
	.vision-table tr:last-child td {
		border-bottom: none;
	}
	
	.eye-label {
		font-weight: 600;
		color: #2c3e50;
	}
	
	.eye-left .eye-label {
		color: #e74c3c;
	}
	
	.eye-right .eye-label {
		color: #3498db;
	}
	
	.data-value {
		color: #2c3e50;
	}
	
	/* 操作按钮区域 */
	.action-section {
	  display: grid;
	  grid-template-columns: repeat(3, 1fr);   
	  gap: 0;                                  
	  margin-top: 0;
	  border-top: 1px solid #ccc;
	}
	
	/* 按钮 */
	.action-btn {
	  width: 100%;
	  height: 76px;                            
	  border: none;
	  border-right: 1px solid #ccc;
	  border-bottom: 1px solid #ccc;
	  border-radius: 0;
	  font-size: 14px;
	  display: flex;
	  flex-direction: column;                  
	  align-items: center;
	  justify-content: center;
	  background: #fff;
	  color: #333;
	  transition: background .15s;
	}
	.action-btn:nth-child(3n) {                
	  border-right: none;
	}
	.action-btn i {
	  font-size: 22px;
	  margin: 0 0 4px 0;
	}
		.action-btn:active {
	  background: #d5d5d5;
	}
	
	@media (max-width: 768px) {
		.scan-section {
			flex-direction: column;
		}
		
		.info-grid {
			grid-template-columns: 1fr;
		}
		
		.action-section {
			grid-template-columns: repeat(2, 1fr);
		  }
		  .action-btn:nth-child(3n) {
			border-right: 1px solid #ccc;          /* 恢复右边线 */
		  }
		  .action-btn:nth-child(2n) {
			border-right: none;                    /* 每行第 2 个去掉 */
		  }
		.vision-table {
			font-size: 13px;
		}
		
		.vision-table th, 
		.vision-table td {
			padding: 6px 8px;
		}
	}
</style>